

<!DOCTYPE html>
<html >
<head>
    <meta charset="utf-8">
    <title></title>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=0">
    <link rel="stylesheet" href="../plugins/layui/css/layui.css?v=${.Config.basic.version}" media="all">
    <link rel="stylesheet" href="../plugins/layui/css/style.css?v=${.Config.basic.version}" media="all">
    <link rel="stylesheet" href="../plugins/layui/css/add.css?v=${.Config.basic.version}" media="all">
    <link rel="stylesheet" href="../layuiadmin/style/admin.css?v=${.Config.basic.version}" media="all">
    <link rel="stylesheet" href="../plugins/zTree/css/metroStyle/metroStyle.css?v=${.Config.basic.version}">
    <style>
        /* .layui-table-view .layui-table td, .layui-table-view .layui-table th {
            padding: 5px 0;
            border-top: 1px solid #404453;
            border-left: 1px solid #404453;
            border-bottom: 1px solid #404453;
            border-right: 1px solid #404453;
        } */
         .ztree li a {
            cursor: pointer;
            color: #333;
        }
    </style>
</head>
<body>

<div class="layui-fluid">
    <div class="layui-row layui-col-space15">
        <div class="layui-col-xs3">
            <div class="layui-card">
                <div class="layui-card-header">

                </div>
                <div class="layui-card-body">
                    <div class="tree-div scroll">
                        <ul id="treeDemo" class="ztree"></ul>
                    </div>
                </div>
            </div>
        </div>
        <div class="layui-col-xs9">
            <div class="layui-card">
                <div class="layui-card-header "><span class="title"></span><a href="javascript:location.reload();" title="刷新">
                        <i class="layui-icon layui-icon-refresh-3"></i>
                    </a></div>
                <div class="layui-card-body">
                    <table class="layui-hide" id="table" lay-filter="table"></table>
                    <script type="text/html" id="table_toolbar">
                        <div class="layui-btn-container">
                            <button class="layui-btn layui-btn-sm layui-btn-normal  layui-hide action-edit" lay-event="add">增加</button>
                        </div>
                    </script>
                </div>

            </div>
        </div>
    </div>
</div>

<script type="text/html" id="table_action_bar">
    <a class="layui-btn layui-btn-normal layui-btn-xs layui-hide action-edit" lay-event="edit">编辑</a>
    <a class="layui-btn layui-btn-danger layui-btn-xs layui-hide action-delete" lay-event="del">删除</a>
</script>

<script src="../plugins/layui/layui.js"></script>
<script src="../plugins/jquery/jquery-3.6.0.js?v=${.Config.basic.version}"></script>
<script src="../plugins/zTree/js/jquery.ztree.core.min.js?v=${.Config.basic.version}"></script>
<script src="../plugins/zTree/js/jquery.ztree.excheck.js?v=${.Config.basic.version}"></script>
<script src="../plugins/zTree/js/jquery.ztree.exedit.js?v=${.Config.basic.version}"></script>
<script>
    var zTree=null;
    var table=null;
    var form=null;
    var iconPicker =null;
    var Table=null;
    var actions=null;
    var token = window.localStorage.getItem("token");
    var user_info=JSON.parse(window.localStorage.getItem("user_info"));
    var func_url="${.func_url}";
    var actions=[];
    token = 'Bearer ' + token;
    var selectTreeNode=null;
    layui.config({
        base: '../layuiadmin/' //静态资源所在路径
    }).extend({
        index: 'lib/index' //主入口模块
    }).use(['index', 'table','form','iconPicker'], function(){
        $ = layui.$;
        form = layui.form;
        table = layui.table;

        $.ajax({
            type: 'GET',
            url: '../Api/User/Actions',
            data: {func_url:func_url},
            beforeSend: function(request) {
                request.setRequestHeader("Authorization", 'Bearer '+window.localStorage.getItem("token"));
            },
            dataType: "json",
            success: function (data) {
                //console.info(data)
                actions=data.data;
                for(var i=0;i<actions.length;i++){
                    $('.action-'+actions[i].action_id).removeClass("layui-hide");
                }
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                layer.msg('加载操作信息失败');
            }
        });

        $.ajax({
            type: 'GET',
            url: '../Api/Action',
            data: {},
            beforeSend: function(request) {
                request.setRequestHeader("Authorization", 'Bearer '+window.localStorage.getItem("token"));
            },
            dataType: "json",
            success: function (data) {
                console.info(data)
                items=data.data;
                var html="";
                for(var i=0;i<items.length;i++){
                    html+="<option value='"+items[i].id+"'>"+items[i].name+"</option>"
                }
                $("select[name='action_id']").html(html);
                form.render("select");
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                layer.msg('加载操作信息失败');
            }
        });

        var tree_setting = {
            view: {
                dblClickExpand: false,
                fontCss: getFont,
                nameIsHTML: true,
                addHoverDom: addHoverDom,
                removeHoverDom: removeHoverDom,
            },
            callback: {
                onClick: treeOnClick
            },
            edit: {
                enable: false,
            },
            data: {
                simpleData: {
                    enable: true,
                    idKey: 'id',
                    pIdKey: 'pid',
                    rootPId: null
                }
            }
        };
        function getFont(treeId, node) {
            return node.font ? node.font : {};
        }

        function addHoverDom(treeId, treeNode) {
            var sObj = $("#" + treeNode.tId + "_span");
            if (treeNode.editNameFlag || $("#addBtn_"+treeNode.tId).length>0) return;
            var addStr = "<span class='button add' nodeid='"+treeNode.tId+"' id='addBtn_" + treeNode.tId
                + "' title='add node' onfocus='this.blur();'></span>";

            var removeStr = "<span class='button remove' nodeid='"+treeNode.tId+"' id='removeBtn_" + treeNode.tId
                + "' title='remove node' onfocus='this.blur();'></span>";
            sObj.after(removeStr);
            sObj.after(addStr);

            var btn = $("#addBtn_"+treeNode.tId);
            if (btn) btn.bind("click", function(event){
                var tid=$(this).attr("nodeid");
                var node = zTree.getNodeByTId(tid);
                if(node.level>=2){
                    layer.alert("无法在继续在第三级面再添加子页面，请在上一级添加。")
                    return false;
                }

                $("input[name='id']").removeAttr("disabled");
                $('#btn_add').removeClass("hide");
                $('#btn_save').addClass("hide");

                $("#btn_cancel").click();
                $('.title').html("新增");
                //console.info(node);

                form.val("func-form", {
                    pid:node.id,
                    level:node.level+1
                });

                return false;
            });
            btn = $("#removeBtn_"+treeNode.tId);
            if (btn) btn.bind("click", function(event){
                var tid=$(this).attr("nodeid");
                var node = zTree.getNodeByTId(tid);
                layer.confirm('确认删除'+node.name+"?", function(index){
                    layer.close(index);
                    $.ajax({
                        type: 'DELETE',
                        url: '../Api/Func',
                        data: {rid:node.id},
                        beforeSend: function(request) {
                            request.setRequestHeader("Authorization", 'Bearer ' + window.localStorage.getItem("token"));
                        },
                        dataType: "json",
                        success: function (data) {
                            //console.info(data)
                            if(data.code>=0){
                                layer.msg('删除成功');
                                window.location.reload();
                            }else{
                                layer.alert('删除失败:'+data.msg);
                            }
                        },
                        error: function (XMLHttpRequest, textStatus, errorThrown) {
                            layer.alert('删除失败');
                        }
                    });
                });

                return false;
            });
        };
        function removeHoverDom(treeId, treeNode) {
            $("#addBtn_"+treeNode.tId).unbind().remove();
            $("#editBtn_"+treeNode.tId).unbind().remove();
            $("#removeBtn_"+treeNode.tId).unbind().remove();
        };
        function treeOnClick(event, treeId, treeNode) {
            selectTreeNode = treeNode;
            console.info(treeNode);
            Table = table.render({
                elem: '#table'
                //,data:data
                ,url:'../Api/ApiMap'
                ,height: 'full-100'
                ,method:'GET'
                ,headers : {'Authorization': 'Bearer '+window.localStorage.getItem("token")}
                ,where: {func_id:treeNode.id}
                ,page: false
                //,limit:30
                ,toolbar: '#table_toolbar' //开启头部工具栏，并为其绑定左侧模板
                ,defaultToolbar: ['']
                ,title: '用户数据表'
                ,even:true
                ,size: 'sm' //小尺寸的表格
                //,skin: 'nob' //无框风格
                ,cols: [[
                    {field:'id', title:'id',hide:true}
                    ,{field:'func_name', title:'功能', sort: true,width:120}
                    ,{field:'api_name', title:'API名称', sort: true,width:150}
                    ,{field:'api', title:'URL', width:200, unresize: false, sort: true}
                    ,{field:'action_name', title:'动作', sort: true,width:80}
                    ,{field:'method', title:'请求',sort: false, width:80}
                    ,{field:'enable_log', title:'日志',sort: false, width:80,align:'center',templet: function(d){
                            var html = "";
                            if(d.enable_log){
                                html+="<span class=\"layui-badge-dot layui-bg-blue\"></span> "
                            }else{

                            }
                            return html;
                        }}
                    


                    ,{title:'', toolbar:'#table_action_bar'}
                ]]
                ,done: function(res, curr, count){
                    for(var i=0;i<actions.length;i++){
                        //console.info(actions[i])
                        $('.action-'+actions[i].action_id).removeClass("layui-hide");
                    }
                }
            });

            //头工具栏事件
            table.on('toolbar(table)', function(obj){
                switch(obj.event){
                    case 'add':
                        onAdd();
                        break;

                };
            });
            //监听行工具事件
            table.on('tool(table)', function(obj){
                var data = obj.data;
                console.log(data)
                if(obj.event === 'del'){
                    onDelete(data);
                }
                else if(obj.event === 'edit'){
                    onEdit(data);
                }
            });
        }

        form.on('submit(btn_ok)', function(data){
            var field = data.field; //获取提交的字段
            var type="";
            if(data.field.id.length==0){
                type="POST";
            }else{
                type="PUT"
            }

            if(data.field.enable_log=="on"){
                data.field.enable_log=1;
            }else{
                data.field.enable_log=0;
            }
            $.ajax({
                type: type,
                url: '../Api/ApiMap',
                data: field,
                beforeSend: function(request) {
                    request.setRequestHeader("Authorization", 'Bearer '+window.localStorage.getItem("token"));
                },
                dataType: "json",
                success: function (data) {
                    //console.info(data)
                    if(data.code>=0){
                        layer.msg('保存成功');
                        layui.table.reload('table'); //重载表格
                        layer.close(lay_index); //再执行关闭
                    }else{
                        layer.alert('保存失败:'+data.msg);
                    }
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    layer.alert('保存失败');
                }
            });
        });


        $.ajax({
            type: 'GET',
            url: '../Api/Func',
            data: {},
            beforeSend: function(request) {
                request.setRequestHeader("Authorization", 'Bearer '+window.localStorage.getItem("token"));
            },
            dataType: "json",
            success: function (data) {
                for(var i=0;i<data.data.length;i++){
                    if(data.data[i].type==0){
                        data.data[i]["icon"]="../plugins/zTree/css/metroStyle/img/html.png";
                    }else{
                        data.data[i]["icon"]="../plugins/zTree/css/metroStyle/img/iframe.png";
                    }
                    data.data[i]['url']="";
                }
                zTree = $.fn.zTree.init($("#treeDemo"), tree_setting, data.data);
                zTree.expandAll(true);
                //下拉框
                var funcs=data.data;
                var html="<option value=\"\">选择</option>";
                for(var i=0;i<funcs.length;i++){
                    if(funcs[i].level<2){
                        html+="<option value=\""+funcs[i].id+"\">"+funcs[i].name+"</option>";
                    }
                }
                $("select[name='pid']").html(html);
                form.render('select');
                form.on('select(pid)', function(data){
                    for(var i=0;i<funcs.length;i++){
                        if(funcs[i].id==data.value){
                            form.val("func-form", {level:funcs[i].level});break;
                        }
                    }
                });
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                layer.msg('加载信息失败');
            }

        });

        resizeElement();
    });

    function onAdd() {
        $("#form")[0].reset();
        form.val("form",{func_id:selectTreeNode.id});
        layer.open({
            //area: 'auto',
            area:['450px','400px'],
            offset: '10%',
            type: 1,
            shade: 0.3,
            shadeClose: true,
            title: '新增', //不显示标题
            content: $('#form'),
            maxmin: false,
            btn: ['确定', '取消'],
            yes: function(index, layero){
                lay_index=index;
                var submit = layero.find("#btn_ok");
                submit.click();
            }
        });
    }

    function onEdit(item) {

        layer.open({
            //area: 'auto',
            area:['450px','400px'],
            type: 1,
            shade: 0.3,
            shadeClose: true,
            offset: '100px',
            title: '修改:'+item.func_name+"->"+item.action_name, //不显示标题
            content: $('#form'), //捕获的元素，注意：最好该指定的元素要存放在body最外层，否则可能被其它的相对元素所影响
            btn: ['确定', '取消']
            ,yes: function(index, layero){
                lay_index=index;
                var submit = layero.find("#btn_ok");
                submit.click();
            }
        });

        layer.load(1);
        $.ajax({
            type: 'GET',
            url:'../Api/ApiMap',
            data: {id:item.id,action_id:item.action_id,func_id:item.func_id},
            beforeSend: function(request) {
                request.setRequestHeader("Authorization", 'Bearer '+window.localStorage.getItem("token"));
            },
            success: function(data){
                if(data){
                    console.info(data.data[0]);
                    if(data.data[0].enable_log){
                        data.data[0].enable_log="on";
                    }else{
                        data.data[0].enable_log="";
                    }
                    form.val("form", data.data[0]);
                }

            },
            complete: function(XMLHttpRequest, textStatus) {
                layer.closeAll('loading');
            },
            dataType: "json"
        });
    }

    function onDelete(item) {
        layer.confirm('确认删除'+item.api+"?", function(index){
            //obj.del();
            layer.close(index);
            $.ajax({
                type: 'DELETE',
                url: '../Api/ApiMap',
                data: item,
                beforeSend: function(request) {
                    request.setRequestHeader("Authorization", 'Bearer '+window.localStorage.getItem("token"));
                },
                dataType: "json",
                success: function (data) {
                    //console.info(data)
                    if(data.code==0){
                        //layer.msg('成功');
                        layui.table.reload('table'); //重载表格
                        layer.close(index); //再执行关闭
                    }else{
                        layer.alert('失败:'+data.msg);
                    }
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    layer.alert('失败');
                }
            });
        });
    }

    $(window).resize(function () {
        //console.info('resize')
        resizeElement();
    });
    function resizeElement() {
        $('.tree-div').height($(window).height()-95);
    }

</script>
<script src="../js/check_screen.js?v=${.Config.basic.version}"></script>

</body>

<form class="layui-form " lay-filter="form" id="form" style="padding: 20px 30px 0 0;display:none;">
    <div class="layui-form-item layui-hide">
        <label class="layui-form-label">api_id</label>
        <div class="layui-input-block">
            <input type="text" name="id" lay-verify="" placeholder="" autocomplete="off" class="layui-input" disabled>
        </div>
    </div>

    <div class="layui-form-item layui-hide">
        <label class="layui-form-label">func_id</label>
        <div class="layui-input-block">
            <input type="text" name="func_id" lay-verify="required" placeholder="" autocomplete="off" class="layui-input" readonly>
        </div>
    </div>

    <div class="layui-form-item">
        <label class="layui-form-label">动作类型</label>
        <div class="layui-input-block">
            <select id="action_id" name="action_id" lay-filter="action_id" lay-verify="" lay-search="">
            </select>
        </div>
    </div>
    <div class="layui-form-item ">
        <label class="layui-form-label">API名称</label>
        <div class="layui-input-block">
            <input type="text" name="api_name" lay-verify="required" placeholder="" autocomplete="off" class="layui-input">
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">URL路径</label>
        <div class="layui-input-block">
            <input type="text" name="api" value="/Api/" lay-verify="" placeholder="/api/xxx" autocomplete="off" class="layui-input">
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">请求类型</label>
        <div class="layui-input-block">
            <select id="method" name="method" lay-filter="method" lay-verify="" lay-search="">
                <option value="GET" selected="">GET</option>
                <option value="PUT/POST">PUT/POST</option>
                <option value="DELETE">DELETE</option>
            </select>
        </div>
    </div>

    <div class="layui-form-item">
        <label class="layui-form-label">记录日志</label>
        <div class="layui-input-block">
            <input type="checkbox" name="enable_log" checked="" lay-skin="switch" lay-text="启用|关闭" >
        </div>
    </div>




    <div class="layui-form-item layui-hide">
        <input type="button" lay-submit lay-filter="btn_ok" id="btn_ok" value="保存">
        <input type="button" lay-submit lay-filter="btn_cancel" id="btn_cancel" value="取消">
    </div>
</form>

</html>

